import re
import datetime
import logging

from google.appengine.ext import db
from google.appengine.api import urlfetch
from google.appengine.api import memcache

from models import *

from friendfeed import *
import utils

_DEFAULT_INTERVAL = 30
_FRIENDFEED_TASK_NAME = 'friendfeed'

class TaskEntity(db.Model):
    name = db.StringProperty()
    next_run = db.DateTimeProperty()
    interval = db.IntegerProperty(default = _DEFAULT_INTERVAL) #default interval is 30 minutes
    
    @classmethod
    def get_task(cls, nameOfTask):
        memcache_id = 'Task:%s' %  nameOfTask
        result = utils.get_from_cache(memcache_id)
        if not (result == None):
            return result
        result = cls.gql('WHERE name=:1', nameOfTask).get()
        if result == None:
            now = datetime.datetime.now()
            one_minutes = datetime.timedelta(minutes = -1)
            next_run = now + one_minutes
            result = cls(key_name = nameOfTask, name=nameOfTask, next_run = next_run)
        memcache.set(memcache_id, result)
        return result
    
    @classmethod
    def update_task(cls, task):
        nameOfTask = task.name
        memcache_id = 'Task:%s' %  nameOfTask
        result = utils.get_from_cache(memcache_id)
        if result == None or result.next_run != task.next_run:
            task.put()
            memcache.set(memcache_id, task)
    
class FriendFeedTask(object):
    @staticmethod
    def run():
        logging.debug('begin to run friend feed task')
        now = datetime.datetime.now()
        task = TaskEntity.get_task(_FRIENDFEED_TASK_NAME)
        next_run = task.next_run
        if now < next_run:
            logging.debug('it is not time for next run')
            return
        session = FriendFeed('eduspur', 'lean752bolas')
        feed = session.fetch_home_feed()
        FriendFeedTask.save_feed(feed)
        interval = datetime.timedelta(minutes = _DEFAULT_INTERVAL)
        task.next_run = now + interval
        TaskEntity.update_task(task)
    
    @staticmethod
    def save_feed(feed):
        logging.debug('begin to save feed')
        entries = feed['entries']
        all_entries = FeedEntry.get_all()
        for entry in entries:
            entry_id = entry['id']
            key_name = 'kn' + entry_id
            if len(filter(lambda entry: entry.key().name() == key_name, all_entries)) == 1:
                continue
            published = entry['published']
            link = entry['link']
            updated = entry['updated']
            title = entry['title']
            service = entry['service']
            feedService = Service.get_service(service['id'], service['profileUrl'], service['entryType'], service['name'])
            feedEntry = FeedEntry(key_name = key_name, entry_id = entry_id, published = published, updated = updated, link = link, title = title, service=feedService)
            feedEntry.save()
            memcache.delete(constants.FEED_FIRST_PAGE_CACHE_KEY)
            
        
    